<template>
  <div class="attendance-apply">
    <el-card class="apply-card">
      <template #header>
        <div class="card-header">
          <span class="header-title">请假申请</span>
          <el-button type="primary" @click="handleAdd" class="add-btn">
            <el-icon><Plus /></el-icon>新增申请
          </el-button>
        </div>
      </template>

      <!-- 表格区域 -->
      <el-table 
        :data="tableData" 
        border 
        style="width: 100%" 
        v-loading="loading"
        class="apply-table"
        :header-cell-style="{
          background: '#f8faff',
          color: '#303133',
          fontWeight: '600',
          fontSize: '14px'
        }"
      >
        <el-table-column prop="createdTime" label="申请日期" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.createdTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="leaveTypeDesc" label="请假类型" width="120">
          <template #default="scope">
            <el-tag effect="light" type="primary">
              {{ scope.row.leaveTypeDesc }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startDate" label="开始日期" width="180" />
        <el-table-column prop="endDate" label="结束日期" width="180" />
        <el-table-column prop="statusDesc" label="状态" width="120">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)" effect="light">
              {{ scope.row.statusDesc }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="reason" label="请假原因" min-width="200" show-overflow-tooltip />
        <el-table-column prop="approvalRemark" label="审批意见" min-width="200" show-overflow-tooltip />
        <!-- <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button 
              link 
              type="primary" 
              :disabled="scope.row.status !== 0"
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button 
              link 
              type="danger" 
              :disabled="scope.row.status !== 0"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column> -->
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
          class="custom-pagination"
        />
      </div>

      <!-- 申请表单对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogType === 'add' ? '新增申请' : '编辑申请'"
        width="500px"
        class="apply-dialog"
      >
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="请假类型" prop="leaveType">
            <el-select v-model="form.leaveType" placeholder="请选择请假类型" class="form-select">
              <el-option label="事假" :value="1" />
              <el-option label="病假" :value="2" />
              <el-option label="年假" :value="3" />
              <el-option label="婚假" :value="4" />
              <el-option label="产假" :value="5" />
              <el-option label="丧假" :value="6" />
              <el-option label="其他" :value="7" />
            </el-select>
          </el-form-item>
          <el-form-item label="开始日期" prop="startDate">
            <el-date-picker
              v-model="form.startDate"
              type="date"
              placeholder="选择开始日期"
              value-format="YYYY-MM-DD"
              class="form-date"
            />
          </el-form-item>
          <el-form-item label="结束日期" prop="endDate">
            <el-date-picker
              v-model="form.endDate"
              type="date"
              placeholder="选择结束日期"
              value-format="YYYY-MM-DD"
              :disabled-date="(time) => time.getTime() < new Date(form.startDate).getTime()"
              class="form-date"
            />
          </el-form-item>
          <el-form-item label="请假原因" prop="reason">
            <el-input
              v-model="form.reason"
              type="textarea"
              rows="3"
              placeholder="请输入请假原因"
              class="form-textarea"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">
              <el-icon><Close /></el-icon>取消
            </el-button>
            <el-button type="primary" @click="handleSubmit" class="submit-btn">
              <el-icon><Check /></el-icon>确定
            </el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getApplyList, createApply } from '@/api/employee/apply'
import { 
  Plus, 
  Check, 
  Close,
  Calendar, 
  Document
} from '@element-plus/icons-vue'

// 加载状态
const loading = ref(false)

// 表格数据
const tableData = ref([])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const form = reactive({
  leaveType: '',
  startDate: '',
  endDate: '',
  reason: ''
})

// 表单校验规则
const rules = {
  leaveType: [{ required: true, message: '请选择请假类型', trigger: 'change' }],
  startDate: [{ required: true, message: '请选择开始日期', trigger: 'change' }],
  endDate: [{ required: true, message: '请选择结束日期', trigger: 'change' }],
  reason: [
    { required: true, message: '请输入请假原因', trigger: 'blur' },
    { min: 2, max: 200, message: '长度在 2 到 200 个字符', trigger: 'blur' }
  ]
}

// 获取状态对应的类型
const getStatusType = (status) => {
  const typeMap = {
    0: 'info',    // 待审批
    1: 'success', // 已通过
    2: 'danger',  // 已拒绝
  }
  return typeMap[status] || 'info'
}

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return ''
  return dateTimeStr.substring(0, 19).replace('T', ' ')
}

// 获取请假申请列表
const fetchApplyList = async () => {
  loading.value = true
  try {
    const employeeNo = localStorage.getItem('employeeNo')
    if (!employeeNo) {
      ElMessage.error('获取员工编号失败')
      return
    }
    const params = {
      employeeNo,
      current: currentPage.value,
      size: pageSize.value
    }
    const res = await getApplyList(params)
    if (res.data) {
      tableData.value = res.data.records
      total.value = res.data.total
    }
  } catch (error) {
    console.error('获取请假申请列表失败：', error)
    ElMessage.error('获取请假申请列表失败')
  } finally {
    loading.value = false
  }
}

// 新增申请
const handleAdd = () => {
  dialogType.value = 'add'
  form.leaveType = ''
  form.startDate = ''
  form.endDate = ''
  form.reason = ''
  dialogVisible.value = true
}

// 编辑申请
const handleEdit = (row) => {
  dialogType.value = 'edit'
  form.leaveType = row.leaveType
  form.startDate = row.startDate
  form.endDate = row.endDate
  form.reason = row.reason
  dialogVisible.value = true
}

// 删除申请
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确认删除该申请记录吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    ElMessage.success('删除成功')
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    const employeeNo = localStorage.getItem('employeeNo')
    if (!employeeNo) {
      ElMessage.error('获取员工编号失败')
      return
    }

    const submitData = {
      employeeNo,
      leaveType: form.leaveType,
      startDate: form.startDate,
      endDate: form.endDate,
      reason: form.reason
    }

    const res = await createApply(submitData)
    if (res.data) {
      ElMessage.success('提交成功')
      dialogVisible.value = false
      fetchApplyList()
    } else {
      ElMessage.error(res.data?.message || '提交失败')
    }
  } catch (error) {
    console.error('提交请假申请失败：', error)
    ElMessage.error('请假开始日期不能是过去的日期')
  }
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchApplyList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchApplyList()
}

// 页面加载时获取数据
onMounted(() => {
  fetchApplyList()
})
</script>

<style scoped lang="scss">
.attendance-apply {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  
  .apply-card {
    border-radius: 12px;
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.05);
    transition: all 0.3s ease;
    overflow: hidden;
    
    &:hover {
      box-shadow: 0 12px 32px rgba(24, 144, 255, 0.1);
      transform: translateY(-2px);
    }
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 20px;
    border-bottom: 1px solid #f0f0f0;
    
    .header-title {
      font-size: 18px;
      font-weight: 600;
      color: #303133;
      position: relative;
      padding-left: 12px;
      
      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 4px;
        height: 18px;
        background: #1890ff;
        border-radius: 2px;
      }
    }
    
    .add-btn {
      background: linear-gradient(135deg, #1890ff, #36a6ff);
      border: none;
      border-radius: 20px;
      padding: 8px 16px;
      transition: all 0.3s ease;
      box-shadow: 0 2px 6px rgba(24, 144, 255, 0.2);
      
      .el-icon {
        margin-right: 4px;
      }
      
      &:hover {
        background: linear-gradient(135deg, #40a9ff, #5cbbff);
        box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
        transform: translateY(-2px);
      }
      
      &:active {
        background: linear-gradient(135deg, #096dd9, #1890ff);
        transform: translateY(0);
      }
    }
  }
  
  .apply-table {
    margin: 16px 0;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
    
    :deep(.el-table__row) {
      transition: all 0.3s;
      
      &:hover {
        background-color: #f8faff !important;
      }
    }
    
    :deep(.el-table__cell) {
      padding: 10px 0;
    }
    
    :deep(.el-tag) {
      padding: 0 10px;
      height: 28px;
      line-height: 28px;
      border-radius: 4px;
      font-weight: 500;
      font-size: 12px;
      
      &.el-tag--success {
        background-color: rgba(82, 196, 26, 0.08);
        border-color: rgba(82, 196, 26, 0.2);
        color: #52c41a;
      }
      
      &.el-tag--info {
        background-color: rgba(144, 147, 153, 0.08);
        border-color: rgba(144, 147, 153, 0.2);
        color: #909399;
      }
      
      &.el-tag--warning {
        background-color: rgba(250, 173, 20, 0.08);
        border-color: rgba(250, 173, 20, 0.2);
        color: #faad14;
      }
      
      &.el-tag--danger {
        background-color: rgba(245, 34, 45, 0.08);
        border-color: rgba(245, 34, 45, 0.2);
        color: #f5222d;
      }
      
      &.el-tag--primary {
        background-color: rgba(24, 144, 255, 0.08);
        border-color: rgba(24, 144, 255, 0.2);
        color: #1890ff;
      }
    }
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
    padding: 10px 0;
    
    :deep(.custom-pagination) {
      padding: 0;
      
      .el-pagination__total {
        margin-right: 16px;
        color: #606266;
        font-weight: 500;
      }
      
      .el-pagination__sizes {
        margin-right: 16px;
        
        .el-select .el-input {
          width: 110px;
          
          .el-input__wrapper {
            background-color: #f5f7fa;
            border-radius: 20px;
          }
        }
      }
      
      button {
        background-color: #f5f7fa;
        border-radius: 4px;
        margin: 0 3px;
        color: #606266;
        transition: all 0.2s ease;
        
        &:hover {
          color: #1890ff;
          background-color: #e6f7ff;
        }
        
        &:disabled {
          color: #c0c4cc;
        }
      }
      
      .btn-prev, .btn-next {
        padding: 0 8px;
        
        &:hover {
          background-color: #e6f7ff;
        }
      }
      
      .el-pager {
        li {
          background-color: #f5f7fa;
          border-radius: 4px;
          margin: 0 3px;
          color: #606266;
          font-weight: 500;
          min-width: 32px;
          transition: all 0.2s ease;
          
          &:hover {
            color: #1890ff;
            background-color: #e6f7ff;
          }
          
          &.is-active {
            background-color: #1890ff;
            color: #fff;
            font-weight: 600;
            box-shadow: 0 2px 6px rgba(24, 144, 255, 0.2);
            
            &:hover {
              background-color: #40a9ff;
            }
          }
        }
      }
      
      .el-pagination__jump {
        margin-left: 16px;
        color: #606266;
        
        .el-input__wrapper {
          background-color: #f5f7fa;
          border-radius: 4px;
        }
      }
    }
  }
  
  :deep(.apply-dialog) {
    border-radius: 12px;
    overflow: hidden;
    
    .el-dialog__header {
      padding: 16px 20px;
      border-bottom: 1px solid #f0f0f0;
      margin: 0;
      
      .el-dialog__title {
        font-size: 18px;
        font-weight: 600;
        color: #303133;
      }
    }
    
    .el-dialog__body {
      padding: 24px;
    }
    
    .el-dialog__footer {
      padding: 16px 20px;
      border-top: 1px solid #f0f0f0;
    }
    
    .el-form-item__label {
      font-weight: 600;
      color: #606266;
    }
    
    .form-select, .form-date {
      width: 100%;
      
      .el-input__wrapper {
        border-radius: 8px;
        box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1) inset;
        
        &:hover, &.is-focus {
          box-shadow: 0 0 0 1px #1890ff inset;
        }
      }
    }
    
    .form-textarea {
      .el-textarea__inner {
        border-radius: 8px;
        padding: 10px 12px;
        min-height: 120px !important;
        box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1) inset;
        transition: all 0.3s;
        
        &:hover, &:focus {
          box-shadow: 0 0 0 1px #1890ff inset;
        }
      }
    }
    
    .dialog-footer {
      .el-button {
        border-radius: 8px;
        padding: 8px 20px;
        font-weight: 500;
        transition: all 0.3s;
        
        .el-icon {
          margin-right: 4px;
        }
        
        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }
      }
      
      .submit-btn {
        background: linear-gradient(135deg, #1890ff, #36a6ff);
        border-color: #1890ff;
        
        &:hover {
          background: linear-gradient(135deg, #40a9ff, #5cbbff);
          border-color: #40a9ff;
        }
      }
    }
  }
}
</style> 